<template>
	<div>
		<div class="container">
			<div class="handle-box">
				<el-input v-model="query.strategyDesc" placeholder="策略描述" class="handle-input mr10"></el-input>
				<el-button type="primary" :icon="Search" @click="handleSearch">搜索</el-button>
				<el-button type="primary" :icon="Plus" @click="handleAdd">新增</el-button>
			</div>
			<el-table :data="tableData"  style="width: 100%">
    <el-table-column type="expand">
      <template #default="props">
        <div m="4">
          <el-table :data="props.row.strategyDetailBriefVOS" >
            <el-table-column label="明细ID" prop="detailId" align="center"/>
            <el-table-column label="奖品ID" prop="awardId" align="center"/>
            <el-table-column label="奖品名称" prop="awardName" align="center"/>
            <el-table-column label="奖品库存" prop="awardCount"  align="center"/>
            <el-table-column label="奖品剩余库存" prop="awardSurplusCount"  align="center"/>
            <el-table-column label="中奖概率" prop="awardRate"  align="center"/>
            <!-- <el-table-column label="创建时间" prop="createTime"  align="center"/>
            <el-table-column label="更新时间" prop="updateTime"  align="center"/> -->
          </el-table>
        </div>
      </template>
    </el-table-column>
     <el-table-column prop="strategyId" label="策略ID" />
      			<el-table-column prop="strategyDesc" label="策略描述"  align="center"/>
      			<el-table-column  label="策略模式" align="center" >
					<template #default="scope">
					<span v-if="scope.row.strategyMode === 1">单项概率</span>
					<span v-else>其他（{{ scope.row.strategyMode }}）</span>
				</template>
				</el-table-column>
      			<el-table-column prop="createTime" label="创建时间"  align="center"/>
      			<!-- <el-table-column prop="updateTime" label="更新时间"  align="center"/> -->
				
				<el-table-column label="操作" width="220" align="center">
					<template #default="scope">
						<el-button text :icon="Edit" @click="handleEdit(scope.$index, scope.row)" v-permiss="15">
							编辑
						</el-button>
						<el-button text :icon="Delete" class="red" @click="handleDelete(scope.$index, scope.row)" v-permiss="16">
							删除
						</el-button>
					</template>
				</el-table-column>
  </el-table>
			 
			<div class="pagination">
				<el-pagination
					background
					layout="total, prev, pager, next"
					:current-page="query.pageNum"
					:page-size="query.pageSize"
					:total="pageTotal"
					@current-change="handlePageChange"
				></el-pagination>
			</div>
		</div>

		<!-- 编辑弹出框 -->
		<el-dialog title="编辑" v-model="editVisible" width="1000px" append-to-body>
			<el-divider>策略配置,用于配置抽奖玩法</el-divider>
		<el-form label-width="70px">
				<el-form-item label="策略描述">
					<el-input v-model="addForm.strategyDesc"></el-input>
				</el-form-item>
				<el-form-item label="策略方式" >
						<!-- 策略方式（1:单项概率、2:总体概率） -->
						<el-select v-model="addForm.strategyMode" placeholder="策略玩法" class="handle-select mr10">
						<el-option key="1" label="单项概率" value="1"></el-option>
					</el-select>
				</el-form-item>
				
			</el-form>
	
	<el-divider>策略明细，用来配置奖品和中奖概率等信息</el-divider>
   <div class="dynamic-form">
	    <!-- 添加按钮 -->
    <el-button @click="addField" type="primary">添加奖品</el-button>

    <el-row :gutter="10" v-for="(item, index) in formItems" :key="index" style="margin-bottom: 15px;">
	
      <!-- 奖品选择 -->
      <el-col :span="6">
        <el-form-item label="选择奖品：" prop="awardType">
			<el-select v-model="item.awardInfo" value-key="awardId" placeholder="请选择奖品">
            <el-option v-for="{awardId, awardName} in awardTypesData" :key="awardId" :label="awardName" :value="{awardId, awardName}"></el-option>
          </el-select>
        </el-form-item>
      </el-col>

      <el-col :span="6">
        <el-form-item label="中奖概率：" prop="awardRate">
          <el-input class="custom-input-width" v-model="item.awardRate" placeholder="奖品概率,0-1之间"></el-input>
        </el-form-item>
      </el-col>

      <!-- 奖品总库存 -->
      <el-col :span="4">
        <el-form-item label="奖品总库存：" prop="awardCount">
          <el-input class="custom-input-width" v-model="item.awardCount" placeholder="奖品总库存"></el-input>
        </el-form-item>
      </el-col>
	  <!-- 奖品总库存 -->
      <el-col :span="4">
        <el-form-item label="剩余库存：" prop="awardSurplusCount">
          <el-input class="custom-input-width" v-model="item.awardSurplusCount" placeholder="奖品剩余库存"></el-input>
        </el-form-item>
      </el-col>

      <!-- 删除按钮 -->
        <el-col :span="4" >
        <el-button @click="removeField(index)" type="danger">删除</el-button>
      </el-col>
    </el-row>
	<el-button  @click="addVisible = false">取 消</el-button>
	<el-button type="primary" @click="saveAdd">确 定</el-button>
  </div>
		</el-dialog>


		<!--  新增  -->
 	<el-dialog title="新增" v-model="addVisible" width="1000px" append-to-body >
		<el-divider>策略配置,用于配置抽奖玩法</el-divider>
		<el-form label-width="70px">
				<el-form-item label="策略描述">
					<el-input v-model="addForm.strategyDesc"></el-input>
				</el-form-item>
				<el-form-item label="策略方式" >
						<!-- 策略方式（1:单项概率、2:总体概率） -->
						<el-select v-model="addForm.strategyMode" placeholder="策略玩法" class="handle-select mr10">
						<el-option key="1" label="单项概率" value="1"></el-option>
					</el-select>
				</el-form-item>
				
			</el-form>
	
	<el-divider>策略明细，用来配置奖品和中奖概率等信息</el-divider>
   <div class="dynamic-form">
	    <!-- 添加按钮 -->
    <el-button @click="addField" type="primary">添加奖品</el-button>

    <el-row :gutter="10" v-for="(item, index) in formItems" :key="index" style="margin-bottom: 15px;">
	
      <!-- 奖品选择 -->
      <el-col :span="6">
        <el-form-item label="选择奖品：" prop="awardType">
			<el-select v-model="item.awardInfo" value-key="awardId" placeholder="请选择奖品">
            <el-option v-for="{awardId, awardName} in awardTypesData" :key="awardId" :label="awardName" :value="{awardId, awardName}"></el-option>
          </el-select>
        </el-form-item>
      </el-col>

      <el-col :span="6">
        <el-form-item label="中奖概率：" prop="awardRate">
          <el-input class="custom-input-width" v-model="item.awardRate" placeholder="奖品概率,0-1之间"></el-input>
        </el-form-item>
      </el-col>

      <!-- 奖品总库存 -->
      <el-col :span="4">
        <el-form-item label="奖品总库存：" prop="awardCount">
          <el-input class="custom-input-width" v-model="item.awardCount" placeholder="奖品总库存"></el-input>
        </el-form-item>
      </el-col>
	  <!-- 奖品总库存 -->
      <el-col :span="4">
        <el-form-item label="剩余库存：" prop="awardSurplusCount">
          <el-input class="custom-input-width" v-model="item.awardSurplusCount" placeholder="奖品剩余库存"></el-input>
        </el-form-item>
      </el-col>

      <!-- 删除按钮 -->
        <el-col :span="4" >
        <el-button @click="removeField(index)" type="danger">删除</el-button>
      </el-col>
    </el-row>
	<el-button  @click="addVisible = false">取 消</el-button>
	<el-button type="primary" @click="saveAdd">确 定</el-button>
  </div>

    </el-dialog>


	</div>
</template>

<script setup lang="ts" name="basetable">
import { ref, reactive } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Delete, Edit, Search, Plus } from '@element-plus/icons-vue';
import { queryStrategyList,addStrategy,queryAwardList, deleteStrategyRelate} from '../api/lottery';


// 添加操作处理
interface AwardItem {
	awardInfo: {
			awardId: string;
			awardName: string;
		};
  	awardRate: string;
  	awardCount: number;
  	awardSurplusCount: number;
}
let addForm = reactive({
	strategyDesc: '',
	strategyMode: '',
	grantType: ''

});
const formItems = ref<AwardItem[]>([{ 
	awardInfo:{
		awardId: '',
		awardName: ''
	},
	// detailId: null,
	awardRate: '',
	awardCount: 0,
	awardSurplusCount:0
}]);


// 新增操作
const addField = () => {
	formItems.value.push({ 
		awardInfo:{
			awardId: '',
			awardName: ''
		},
		awardRate: '',
		awardCount: 0,
		awardSurplusCount:0
	});
};
// 删除操作
const removeField = (index: number) => {
  formItems.value.splice(index, 1);
};
const saveAdd = () => {
   // 创建一个新对象用于存储聚合后的策略信息
  const strategy = {
    strategyBriefVO: (addForm),
    strategyDetailBriefVOS: formItems.value,
  };

  console.log("聚合后的值：",JSON.stringify(strategy))

  // 校验操作
  // 聚合策略明细和策略配置为一个对象
	addStrategy(strategy).then(res => {
		if(res.data.code === "0000"){
				ElMessage.success(res.data.info);
				addVisible.value = false;
				getData();
			}else{
				ElMessage.error(res.data.info);
			}
	})
}

  
// 查询
interface StrategyDetailBriefVO{
  detailId: number
  awardId: number
  awardName: string
  awardCount: number
  awardSurplusCount: number,
  awardRate: number,
  createTime: string,
  updateTime: string
}

// 表格数据
interface TableItem {
	strategyId: number;
	strategyDesc: string;
	strategyMode: number;
	createTime: string;
	updateTime: string;
	strategyDetailBriefVOS:StrategyDetailBriefVO[]
}

const query = reactive({
	strategyDesc: null,
	pageNum: 0,
	pageSize: 10
});
const tableData = ref<TableItem[]>([]);
const pageTotal = ref(0);
// 获取表格数据
const getData = () => {
	queryStrategyList(query).then(res => {
		tableData.value = res.data.strategyAggreatesList;
		console.log(JSON.stringify(tableData.value))
		pageTotal.value = res.data.count || 0;
	});
};
getData();


interface AwardTypes {
	awardId:string,
	awardName:string
}
const awardTypesData = ref<AwardTypes[]>([]);
// 获取下拉框奖品数据
const getAwardData = () => {
	queryAwardList(null).then(res => {
		console.log(res)
		awardTypesData.value=res.data.awardVOList
	});
};
// 获取奖品
getAwardData();

// 查询操作
const handleSearch = () => {
	query.pageNum = 1;
	getData();
};
// 分页导航
const handlePageChange = (val: number) => {
	query.pageNum = val;
	getData();
};

// 删除操作
const handleDelete = (index: number, row: any) => {
	// 二次确认删除
	ElMessageBox.confirm('确定要删除吗？', '提示', {
		type: 'warning'
	})
		.then(() => {
			deleteStrategyRelate(row.strategyId).then((resp) => {
				if (resp.data.code == "0000") {
					ElMessage.success('删除成功');
					tableData.value.splice(index, 1);
				} else {
					ElMessage.warning(resp.data.info);
				}

			})
		})
		.catch(() => {});
};
// 添加
const addVisible = ref(false);

  const handleAdd = () => {
	addVisible.value =true
  }



// 表格编辑时弹窗和保存
const editVisible = ref(false);
let editForm = ref({
	strategyDesc: '',
	strategyMode: '',
	grantType: ''
});
let idx: number = -1;
const handleEdit = (index: number, row: any) => {
	idx = index;
	editForm.value = row;
	editVisible.value = true;
};
const saveEdit = () => {
	editVisible.value = false;
	ElMessage.success(`修改第 ${idx + 1} 行成功`);
	
};
</script>

<style scoped>

.handle-box {
	margin-bottom: 20px;
}

.handle-select {
	width: 120px;
}

.handle-input {
	width: 300px;
}
.table {
	width: 100%;
	font-size: 14px;
}
.red {
	color: #F56C6C;
}
.mr10 {
	margin-right: 10px;
}
.table-td-thumb {
	display: block;
	margin: auto;
	width: 40px;
	height: 40px;
}
</style>
